package com.gx.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.gx.common.result.AppResult;
import com.gx.model.dto.common.BaseQueryDto;
import com.gx.model.dto.definition.FlowSaveXmlDto;
import com.gx.model.pojo.TbBusinessDeploy;
import com.gx.model.vo.FlowLineVo;
import com.gx.model.vo.FlowNodeVo;
import com.gx.model.vo.FlowProcDefVo;
import com.gx.service.FlowDefinitionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author Liu-pj
 * @Date 2022/9/14 12:16
 * @Desc 工作流程定义
 **/
@ApiSort(21)
@Slf4j
@Api(tags = "定义管理")
@RestController
@RequestMapping("/flowable/definition")
public class FlowDefinitionController {

    @Autowired
    private FlowDefinitionService flowDefinitionService;

    @PostMapping(value = "/list")
    @ApiOperation(value = "流程定义列表")
    public AppResult<Page<FlowProcDefVo>> list(@RequestBody BaseQueryDto queryDto) {
        return AppResult.success(flowDefinitionService.list(queryDto));
    }

    @GetMapping(value = "/getNodeList")
    @ApiOperation(value = "流程节点详情列表")
    public AppResult<List<FlowNodeVo>> getNodeList(@ApiParam("流程定义id") @RequestParam String processId) {
        return AppResult.success(flowDefinitionService.getNodeList(processId));
    }

    @GetMapping(value = "/getLineList")
    @ApiOperation(value = "流程走线详情列表")
    public AppResult<List<FlowLineVo>> getLineList(@ApiParam("流程定义id") @RequestParam String processId) {
        return AppResult.success(flowDefinitionService.getLineList(processId));
    }

    @ApiOperation(value = "导入流程文件", notes = "上传bpmn20的xml文件")
    @PostMapping("/import")
    public AppResult<String> importFile(@RequestParam(required = false) String name,
                                        @RequestParam(required = false) String category,
                                        @RequestPart @RequestParam("file") MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            flowDefinitionService.importFile(name, category, in);
        } catch (Exception e) {
            return AppResult.failure(e.getMessage(), 500);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }
        return AppResult.success("导入成功");
    }


    @ApiOperation(value = "读取流程定义xml文件")
    @GetMapping("/readXml/{deployId}")
    public AppResult<String> readXml(@ApiParam(value = "流程部署id") @PathVariable(value = "deployId") String deployId) {
        try {
            return AppResult.success(flowDefinitionService.readXml(deployId));
        } catch (Exception e) {
            return AppResult.failure("加载xml文件异常", 500);
        }
    }

    @ApiOperation(value = "读取流程定义图片")
    @GetMapping("/readImage/{deployId}")
    public void readImage(@ApiParam(value = "流程部署id") @PathVariable(value = "deployId") String deployId,
                          HttpServletResponse response) {
        OutputStream os = null;
        BufferedImage image;
        try {
            image = ImageIO.read(flowDefinitionService.readImage(deployId));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation(value = "保存流程设计器内的xml文件")
    @PostMapping("/save")
    public AppResult<String> save(@RequestBody FlowSaveXmlDto dto) {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(dto.getXml().getBytes(StandardCharsets.UTF_8));
            flowDefinitionService.importFile(dto.getName(), dto.getCategory(), in);
        } catch (Exception e) {
            return AppResult.success(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }
        return AppResult.success("导入成功");
    }

    @ApiOperation(value = "激活或挂起流程定义")
    @PostMapping(value = "/updateState")
    public AppResult<String> updateState(@ApiParam(value = "流程部署ID", required = true) @RequestParam String deployId) {
        flowDefinitionService.updateState(deployId);
        return AppResult.success();
    }

    @ApiOperation(value = "删除流程定义")
    @GetMapping(value = "/delete/{deployId}")
    public AppResult<String> delete(@ApiParam(value = "流程部署ID", required = true) @PathVariable String deployId) {
        flowDefinitionService.delete(deployId);
        return AppResult.success();
    }

    /**
     * 挂载流程业务
     */
    @ApiOperation("绑定流程业务")
    @PostMapping("/bindDeployBusiness")
    public AppResult<String> bindDeployBusiness(@RequestBody TbBusinessDeploy deployBusiness) {
        flowDefinitionService.bindDeployBusiness(deployBusiness);
        return AppResult.success("绑定成功");
    }

    /**
     * 根据业务标识查询流程信息
     *
     * @param businessKey 业务标识
     * @return 绑定信息
     */
    @ApiOperation("根据业务标识查询流程id")
    @PostMapping("/getDeployBusiness")
    public AppResult<TbBusinessDeploy> getDeployBusiness(
            @ApiParam(value = "业务标识", required = true)
            @RequestParam String businessKey) {
        TbBusinessDeploy deployBusiness = flowDefinitionService.getDeployBusiness(businessKey);
        return AppResult.success(deployBusiness);
    }
}